#include "relay.h"

// 0-65535
void RELAY_Config(uint16_t Period, uint16_t Prescaler)
{
	//先开时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOF, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,  ENABLE);	//TIM2在APB1总线
	
	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef TIM_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;	//配置推挽输出
	GPIO_InitStructure.GPIO_Pin = RELAY;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
	GPIO_Init(RELAY_PORT, &GPIO_InitStructure);
	
	//继电器输入一个高电平信号是工作状态，所以先初始化低电平
	GPIO_ResetBits (RELAY_PORT, RELAY);	//LOW
	
	TIM_InitStructure.TIM_Period    = Period;	//重装载值
	TIM_InitStructure.TIM_Prescaler = Prescaler;	//预分频值
	TIM_InitStructure.TIM_ClockDivision = TIM_CKD_DIV1;	//时钟分割无
	TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up;	//向上计数
	TIM_InitStructure.TIM_RepetitionCounter = DISABLE;	//先禁用 重复计数次数
	TIM_TimeBaseInit(TIM2, &TIM_InitStructure);	//初始化
	
	//开中断之前，先清空中断!!!
	TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
	
	//开启中断，要或 | 上触发中断源TIM_IT_Trigger
	TIM_ITConfig(TIM2, TIM_IT_Update | TIM_IT_Trigger, ENABLE);
	TIM_Cmd(TIM2, ENABLE);
	
	//中断优先级分组，先随意，因为没有多个中断同时触发
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
	NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;	//中断源
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;//抢占
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;//响应
	NVIC_Init(&NVIC_InitStructure);
	
}


void TIM2_IRQHandler(void)
{
	if (TIM_GetITStatus (TIM2, TIM_IT_Update) == SET)	//判断TIM_GetITStatus == 1 判断是否进入中断
	{
		//写位操作		//SET - GPIO_ReadOutputDataBit  1-读取到的输出状态位，就是取非操作
		GPIO_WriteBit (RELAY_PORT, RELAY, (BitAction)(SET - GPIO_ReadOutputDataBit(RELAY_PORT, RELAY) ) );
		TIM_ClearITPendingBit(TIM2, TIM_IT_Update);	//清空中断
	}
}




